import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";
import { NulResponse, createRequest } from "./common";
import { getRequest } from "../util/Auth";

interface PersonalInformation {
  uid: number;
  name: string;
  userName: string;
  gender: 'male' | 'female';
  post: string;
}

interface PersonalInformationState extends PersonalInformation {

}

interface UpdateNameRequest {
  uid: number;
  name: string;
}

interface UpdateNameResponse {
  name: string;
}

const initialState: PersonalInformationState = {
  uid: -1,
  name: '',
  userName: '',
  gender: 'male',
  post: ''
};

export const fetchPersonalInformation = createAsyncThunk('api/personalInformation', async (_, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<PersonalInformation>>('/service/user/userInfo');
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const updatePersonalName = createAsyncThunk('api/updatePersonalName',
  async (updateNameRequest: UpdateNameRequest, { getState, rejectWithValue }) => {
    const state = getState() as RootState;
    try {
      const request = getRequest(state);
      const response = await request.post<NulResponse<UpdateNameResponse>>('/service/user/updateName',
        createRequest({
          uid: updateNameRequest.uid,
          name: updateNameRequest.name
        })
      );
      return response.data;
    }
    catch (e) {
      return rejectWithValue(e);
    }
  });

const slice = createSlice({
  name: 'test',
  initialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(fetchPersonalInformation.fulfilled, (state, action) => {
      state.uid = action.payload.result.uid;
      state.name = action.payload.result.name;
      state.gender = action.payload.result.gender;
      state.post = action.payload.result.post;
      state.userName = action.payload.result.userName;
    }).addCase(fetchPersonalInformation.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(updatePersonalName.fulfilled, (state, action) => {
      state.name = action.payload.result.name;
      console.log(state.name);
    }).addCase(updatePersonalName.rejected, (state, action) => {
      console.error(action.error);
    });
  }
});

export const { actions } = slice;
export const selectUid = (state: RootState) => state.personalInformation.uid;
export const selectName = (state: RootState) => state.personalInformation.name;
export const selectUserName = (state: RootState) => state.personalInformation.userName;
export const selectGender = (state: RootState) => state.personalInformation.gender;
export const selectPost = (state: RootState) => state.personalInformation.post;
export default slice.reducer;
